package com.hcl.security.domain;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class LoginUser implements UserDetails {

	private User user;

	private String username;

	private String password;

	/**
	 * 自定义权限集合
	 */
	private List<String> permissions;

	public LoginUser() {
	}

	public LoginUser(User user, String username, String password,
			List<String> permissions) {
		this.user = user;
		this.username = username;
		this.password = password;
		this.permissions = permissions;
	}

	/**
	 * security要求权限类型（让自定义的转为当前类型，在security内部使用），不进行序列化
	 */
	@JsonIgnore
	private List<SimpleGrantedAuthority> authorities;

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		// 只在第一次进行类型转换
		if (authorities == null) {
			authorities = permissions.stream().map(SimpleGrantedAuthority::new)
					.collect(Collectors.toList());
		}

		return authorities;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Override
	public String getPassword() {
		return password;
	}

	@Override
	public String getUsername() {
		return username;
	}
}
